package com.ymttest.business.service;

import java.util.ArrayList;
import java.util.Date;
import java.util.Map;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import com.ymatou.iapi.sellerproduct.service.ChangeNewProductInfoCall;
import com.ymt.core.tool.Logger;
import com.ymttest.database.mongo.ActivityProductModelWapper;
import com.ymttest.database.mongo.LiveProductModelWapper;
import com.ymttest.database.mongo.ProductDetailModelWapper;
import com.ymttest.database.sqlwapper.YmtCatalogsIWapper;
import com.ymttest.database.sqlwapper.YmtOrdersWapper;
import com.ymttest.utils.MapUtil;
import com.ymttest.utils.YMTDateUtil;

public class BuyerAppProdService {
	
	private static ChangeNewProductInfoCall changenewproductinfoCall = new ChangeNewProductInfoCall();
	
	/**
	 * 修改商品
	 * 
	 * @return String
	 * @throws JSONException 
	 * @throws Exception
	 */
	public String modifyProduct(String sellerName, int sellerId) throws JSONException, Exception {
		String productId = SellerProductCallService.addNewProductNotOnSale(sellerId, sellerName, 
				MapUtil.hashMap("Product->IsNew",false)).getJSONObject("Data").getString("ProductID");
		//获取规格
		String catalogsId = new YmtCatalogsIWapper().selectCatalogsByProductId(productId).get(0).getsCatalogId();	

		//modify product and on sale 
		Map<String, Object> updateMap = MapUtil.hashMap("LoginID", sellerName, "UserID", sellerId,
														"Product->sProductId",productId,"ProductID",productId,
														"Product->Catalogs[2]->CatalogId",catalogsId,
														"Product->MobileDescription","PC端修改商品",
														"Product->ProductName","PC端修改商品名称",
														"Product->ProductDescriptionInfo->WordContent","修改过商品描述",
														"Product->ProductDescriptionInfo->Pictures[0]->PictureUrl","http://pc1.img.ymatou.com/G01/shangou/M00/2C/A9/rBBlD1gAf_2AQ4GrAANhqAY9_CQ541_1_1_n_w_o.jpg");
		
		String fileName = "changenewproductinfocalltpl_001.json";
		changenewproductinfoCall.callAndGetReturnData(fileName,updateMap);
		
		return productId;
	}
	
	/**
	 * 判断商品的类型（活动、现货、直播）
	 * 
	 * @param productId
	 * @return Integer(1:直播，2：现货， 3：活动)
	 * @throws JSONException 
	 * @throws Exception
	 */
	@SuppressWarnings("rawtypes")
	public int getProductTypeFromMongo(String productId) throws Exception {
		int productType = 2;

		LiveProductModelWapper liveProductModelWapper = new LiveProductModelWapper();
		ActivityProductModelWapper activityProductModelWapper = new ActivityProductModelWapper();
		
		ArrayList<Map> activityProductModelMapList = activityProductModelWapper.getActivityMapByProductId(productId);
		
		for (Map activityProduct : activityProductModelMapList) {
			if(activityProduct != null && new Date().getTime() < this.getCST2TimeStamp(activityProduct.get("EndTimeOfProductInActivity").toString())
					&& !Boolean.valueOf(activityProduct.get("IsTradeIsolation").toString())) {
				
				JSONArray catalogList = new JSONArray(activityProduct.get("CatalogList").toString());
				int size = 0;
				for (int i = 0; i < catalogList.length(); i++) {
					if(this.getCatalogStockFromMongo(1, productId, catalogList.getString(i)).getInt("Stock") == 0){
						size = size + 1;
					}
				}
				
				if (catalogList.length() == size)
					break;
				
				productType = 3;
				break;
			}
		}
		
		Map<String, Object> liveProductModelMap = liveProductModelWapper.getByProductId(productId);
		if(liveProductModelMap != null && 
				new Date().getTime() < this.getCST2TimeStamp(liveProductModelMap.get("EndTime").toString()))
			productType = 1;
		
		return productType;
	}
	
	/**
	 * 根据productId、catalogId获取规格信息
	 * 
	 * @param productId，catalogId
	 * @return JSONObject
	 * @throws JSONException 
	 * @throws Exception
	 */
	public JSONObject getCatalogFromMongo(String productId, String catalogId) throws Exception {
		ProductDetailModelWapper productDetailModelWapper = new ProductDetailModelWapper();
		JSONObject catalogObject = null;
		
		if (null != productDetailModelWapper.getProductId(productId)) {
			JSONArray catalogList = new JSONArray(productDetailModelWapper.getProductId(productId).get("CatalogList").toString());
			
			for(int i = 0; i < catalogList.length(); i++) {
				if (catalogList.getJSONObject(i).getString("CatalogId").equalsIgnoreCase(catalogId))
				{
					catalogObject = catalogList.getJSONObject(i);
					break;
				}
			}
		} else {
			Logger.comment("商品" + productId + "找不到对应的规格" + catalogId);
		}
		
		return catalogObject;
	}
	
	/**
	 * 根据stockType, productId, catalogId获取规格的库存
	 * 
	 * @param productId，catalogId,stockType(0:普通规格，1：活动规格)
	 * @return JSONObject
	 * @throws JSONException 
	 * @throws Exception
	 */
	public JSONObject getCatalogStockFromMongo(int stockType, String productId, String catalogId) throws Exception {
		JSONObject catalogObject = null;
		JSONObject catalogStockObject = null;
		
		if (null != this.getCatalogFromMongo(productId, catalogId)) {
			catalogObject = this.getCatalogFromMongo(productId, catalogId);
			
			JSONArray stockList = catalogObject.getJSONArray("StockList");
			for (int i = 0; i < stockList.length(); i++) {
				if (stockType == stockList.getJSONObject(i).getInt("StockType")) {
					catalogStockObject = stockList.getJSONObject(i);
					break;
				}
			}
		}

		return catalogStockObject;
	}
	
	/**
	 * 根据priceType, productId, catalogId获取规格的价格
	 * 
	 * @param productId，catalogId,priceType(0:原价，1：新客价， 2：VIP价， 3：活动价，5：定金价)
	 * @return JSONObject
	 * @throws JSONException 
	 * @throws Exception
	 */
	public JSONObject getCatalogPriceFromMongo(int priceType, String productId, String catalogId) throws Exception {
		JSONObject catalogObject = null;
		JSONObject catalogPriceObject = null;
		
		if (null != this.getCatalogFromMongo(productId, catalogId)) {
			catalogObject = this.getCatalogFromMongo(productId, catalogId);
			
			JSONArray priceList = catalogObject.getJSONArray("PriceList");
			for (int i = 0; i < priceList.length(); i++) {
				if (priceType == priceList.getJSONObject(i).getInt("PriceType")) {
					catalogPriceObject = priceList.getJSONObject(i);
					
					if (catalogPriceObject.getInt("Price") == 0)
						catalogPriceObject = priceList.getJSONObject(0);
					break;
				}
			}
		}

		return catalogPriceObject;
	}
	
	/**
	 * 根据uesrId, sellerId, productId, catalogId获取规格的价格
	 * 
	 * @param uesrId, sellerId, productId, catalogId
	 * @return JSONObject
	 * @throws JSONException 
	 * @throws Exception
	 */
	public JSONObject getCatalogPriceFromMongo(int uesrId, int sellerId, String productId, String catalogId) throws Exception {
		int priceType = 0;
		JSONObject catalogPriceObject = new JSONObject();
		
		YmtOrdersWapper ymtOrdersWapper = new YmtOrdersWapper();
		if (ymtOrdersWapper.selectAppSellerOrdersTestData(1, "iUserId = " + uesrId + " AND iBuyerId = " + sellerId).size() == 0)
			priceType = 1;
		else if(ymtOrdersWapper.selectAppSellerOrdersTestData(1, "iUserId = " + uesrId + " AND iBuyerId = " + sellerId + " AND iTradingStatus = 4").size() != 0) {
			priceType = 2;
		}
		
		if (null != this.getActivityByCatalogIdFromMongo(productId, catalogId))
			priceType = 3;
		
		ymtOrdersWapper.close();
		catalogPriceObject= this.getCatalogPriceFromMongo(priceType, productId, catalogId);

		return catalogPriceObject;
	}
	
	/**
	 * 
	 * 获取商品规格的属性名称
	 * @param productId, catalogId
	 * @return Integer(如果找到catalogId且商品没有过期，则返回0，否则返回2)
	 * @throws JSONException 
	 * @throws Exception
	 */
	public JSONArray getPropertyListFromMongo(String productId, String catalogId) throws Exception {
		
		JSONArray propertyList = new JSONArray();
		
		ProductDetailModelWapper productDetailModelWapper = new ProductDetailModelWapper();
		Map<String, Object> productDetailModelMap = productDetailModelWapper.getProductId(productId);
		
		JSONArray catalogList = new JSONArray(productDetailModelMap.get("CatalogList").toString());
		for (int i = 0; i < catalogList.length(); i++) {
			if (catalogList.getJSONObject(i).getString("CatalogId").equalsIgnoreCase(catalogId))
				propertyList = catalogList.getJSONObject(i).getJSONArray("PropertyList");
		}
		
		return propertyList;
	}
	
	/**
	 * 
	 * 根据productId, catalogId获取活动信息
	 * @param productId, catalogId
	 * @return JSONObject
	 * @throws JSONException 
	 * @throws Exception
	 */
	@SuppressWarnings("rawtypes")
	public Map getActivityByCatalogIdFromMongo(String productId, String catalogId) throws Exception {
		ActivityProductModelWapper activityProductModel = new ActivityProductModelWapper();
		
		Map activityProductMap = null;
		
		ArrayList<Map> activityProductMapList = activityProductModel.getActivityMapByProductId(productId);
		if (null == activityProductMapList || activityProductMapList.size() == 0)
			return activityProductMap;
		
		for(Map activityProduct : activityProductMapList) {
			JSONArray catalogList = new JSONArray(activityProduct.get("CatalogList").toString());
			
			int size = 0;
			for (int i = 0; i < catalogList.length(); i++) {
				if(this.getCatalogStockFromMongo(1, productId, catalogList.getString(i)).getInt("Stock") == 0){
					size = size + 1;
				}
			}
			
			if (catalogList.length() == size)
				continue;
			
			if (this.getCatalogStockFromMongo(1, productId, catalogId).getInt("Stock") == 0)
				continue;
			
			if (new Date().getTime() > this.getCST2TimeStamp(activityProduct.get("EndTimeOfProductInActivity").toString()) || 
					Boolean.parseBoolean(activityProduct.get("IsTradeIsolation").toString()))
				continue;
			
			for (int i = 0; i < catalogList.length(); i++) {
				String catalogIdFromMongo = catalogList.getString(i);
				
				if (catalogIdFromMongo.equalsIgnoreCase(catalogId)) {
					activityProductMap = activityProduct;
				}
			}
		}
		
		return activityProductMap;
	}
	
	/**
	 * 
	 * 替换_o图片为_lb
	 * @param originUrl
	 * @return String
	 * @throws JSONException 
	 * @throws Exception
	 */
	public String changeProductImageSize(String originUrl) {
		String changeUrl = "";
		String subString = originUrl.substring(0, originUrl.length() - 4);
		
		if ((originUrl.contains("shangou") || originUrl.contains("product")) && subString.endsWith("_n_w_o")) {
			changeUrl = subString.substring(0, subString.length() - 1) + "lb.jpg";
		} else {
			changeUrl = originUrl;
		}
		
		return changeUrl;
	}
	
	public long getCST2TimeStamp(String dateStr) {
		return YMTDateUtil.CST2TimeStamp(dateStr);
	}
	
	public static void main(String[] args) throws Exception {
		BuyerAppProdService service = new BuyerAppProdService();
		System.out.println(service.getCatalogPriceFromMongo(20565876, 20566122, "ffcfdc48-1795-40db-aa19-f4df4d575602", "bc319e37-d34f-4a1a-99aa-63a8dc89411b"));
	}
}
